
class Register(object):

    def __init__(self, name):
        self._name = name
        self._module_dict = dict()

    def register_module(self, obj):
        module_name = obj.__name__
        if module_name in self._module_dict:
            raise KeyError('{} is already registered in {}'.format(
                module_name, self.name))
        self._module_dict[module_name] = obj
        return obj

    def get(self, key):
        return self._module_dict[key]


def build_module(cfg, register_type, default_cfg=None):
    assert isinstance(cfg, dict)
    input_cfg = cfg.copy()
    obj_cls = register_type.get(input_cfg.pop('type'))
    if default_cfg is not None:
        for key, value in default_cfg.items():
            input_cfg.setdefault(key, value)
    return obj_cls(**input_cfg)

